<?php

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded  = ['password_confirmation'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    // 用户组
    public function group()
    {
        return $this->belongsTo('App\Models\Group', 'gid');
    }

    // 部门
    public function department()
    {
        return $this->belongsTo('App\Models\Department', 'department_id');
    }

    // 区域
    public function region()
    {
        return $this->belongsTo('App\Models\Department', 'region_id');
    }

    public function setUsernameAttribute($value)
    {
        $this->attributes['username'] = trim($value);
    }

    public function scopeDesigner($query)
    {
        return $query->where('gid', 3);
    }

    public function scopeSaler($query)
    {
        return $query->whereIn('gid', [5, 6]);
    }  

    public function can($ability, $arguments = [])
    {
        if (!empty($this->group->permissions)) {
            return in_array($ability, $this->group->permissions);
        }
        
        return false;
    } 

    public function isAdmin()
    {
        return $this->group->level == 10;
    }
}
